import {
    createRouter,
    createWebHashHistory
} from 'vue-router'

import {
    defineAsyncComponent
} from 'vue'

import Layout from '@/layout/index.vue'
import Login from '@/views/login/index.vue'
import Home from '@/views/home/index.vue'
import About from '@/views/about/index.vue'
// import NotFound from '@/views/error/404.vue'

// const _import = (path) => defineAsyncComponent(() => import(`@/views/${path}`));

const router = createRouter({
    history: createWebHashHistory(),
    routes: [{
        path: '/',
        name: 'layout',
        redirect: '/home',
        component: Layout,
        children: [{
            path: '/home',
            name: 'home',
            meta: {
                title: '首页'
            },
            component: Home
        }, {
            path: '/about',
            name: 'about',
            meta: {
                title: '关于我们'
            },
            component: About
        }]
    }, {
        path: '/login',
        name: 'login',
        component: Login
    }, {
        path: '/:cathchAll(.*)',
        name: 'notFound',
        component: () => import( /* webpackChunkName: "404" */ '@/views/error/404.vue')
    }]
})


router.beforeEach((to, from, next) => {
    const token = window.localStorage.getItem('token')
    if (token) {
        if (to.path === '/login') {
            next({
                path: '/home'
            })
        } else {
            next()
        }
    } else {
        if (to.path === '/login') {
            next()
        } else {
            next({
                path: '/login'
            })
        }
    }
})

export default router